<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 速云
 */
class SuyunController extends PayController{
    protected $config;

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>'031']);
        }

        //$product = M("Product")->where(["id"=> I("request.pay_bankcode","")])->find();
        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>'031']);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );


        $data = array();
        $data['customer_id'] = $this->config['mch_id'];
        $data['order_id'] = $return['orderid'];
        $data['total_fee'] = $return['amount']*100;
        $data['nonce_str'] = md5(date("YmdHis",time()).mt_rand(10000,99999));
        //$data['notify_url'] = "http://gw.cili123.com.cn/Pay_changzhifu_notifyurl";

        switch($this->config['paytype']){
            //微信
            case 1:
                $data['payment'] .= 'wxpay';
                break;
            //微信H5
            case 2:
                $data['payment'] .= 'wxpay';
                break;
            //银联扫码
            case 11:
                $data['payment'] .= 'unipay';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>'031']);
        }
        $data['remark'] = 'a';

        ksort($data);
        $str = httpstr($data)."&key=".$this->config['signkey'];

        //$str = "customer_id=" . $data['customer_id'] . "&nonce_str=" . $data['nonce_str'] . "&order_id=" . $data['order_id'] . "&total_fee=" . $data['total_fee'] . "&key=" . $this->config['signkey'];
        $data['sign'] = md5($str);
        $data['notify_url'] = $return['notifyurl'];
        $data['client_ip'] = getIP();
        $data['user_agent'] = 'chrome';

        $post = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->config['gateway']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);//允许请求的链接跳转
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $content = $origin =curl_exec($ch);
        $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);//获取最终请求的url地址


        $content = json_decode($content, true);
        /*echo '<pre/>';
        echo "signstr: ".$str.'<br/>';
        var_dump($origin);
        print_r($data);
        print_r($content);
        echo $redirect_url.'<br/>'; */

        if($redirect_url) {
            //echo $redirect_url;exit;
            header('Location: '.$redirect_url); exit;
        } else {
            $c = json_decode($content, true);
            $this->showmessage($c['errmsg'],['code'=>'031']);
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = I("get.");
        /*$p = array (
            'customer_id' => 'xhr027',
            'order_id' => '201809271931178029275',
            'out_transaction_id' => '180927-480911688470512',
            'pay_result' => '0',
            'remark' => 'a',
            'total_fee' => '10000',
            'sign' => 'ad8792ffd2581cd0cf5d63c49e9532ae',
        );*/

        if(empty($p)){
            exit("no_data");
        }

        $sign = $p['sign'];

        //获取订单信息
        $orderid = $p['order_id'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['out_transaction_id'])
        ));

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>'Suyun']);
        if(!$this->config){
            $this->config = M("Channel")->where(array('code'=>'Suyun'))->find();
        }

        if(!$this->config){
            exit("get_tongdao_fail");
        }

        if(intval($p['pay_result']) != 0){
            exit("pay_fail");
        }

        //sign=md5(customer_id=xxx&order_id=xxx&out_transaction_id=xxx&[remark=xxx&]pay_result=xxx&total_fee=xxx&key=xxx).ToLower()

        $arr = [
            'customer_id'=>$p['customer_id'],
            'order_id'=>$p['order_id'],
            'out_transaction_id'=>$p['out_transaction_id'],
            'remark'=>$p['remark'],
            'pay_result'=>$p['pay_result'],
            'total_fee'=>$p['total_fee'],
        ];
        //$str = "customer_id={$p['customer_id']}&order_id={$p['order_id']}&out_transaction_id={$p['out_transaction_id']}&remark={$p['remark']}&pay_result={$p['pay_result']}&total_fee={$p['total_fee']}&key={$this->config['signkey']}";
        ksort($arr);
        $str = httpstr($arr)."&key={$this->config['signkey']}";

        $sign2 = md5($str);

        //echo 'str: '.$str.'<br/><br/>';
        //echo 'sign: '.$sign.'<br/>';
        //echo 'sign2:'.$sign2.'<br/>';
        if($sign != $sign2){
            echo 'sign_wrong';exit;
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Suyun",0);

        //回调成功
        echo 'success'; exit;
    }

    public function callBackUrl(){
        echo '处理成功'; exit;
    }

    public function getBankName($code){
        $ret = '';

        //农业银行 ABC 建设银行 CCB 兴业银行 CIB 招商银行 CMB 民生银行 CMBC 华夏银行 HXB
        //工商银行 ICBC 上海银行 BOSH 中国银行 BOC 交通银行 COMM 上海浦东发展银行 SPDB 广东发展银行 GDB 平安银行 PINGAN 邮政储蓄 PSBC 上海农村商业银行 SHRCB 北京银行 BOB 广州商业银行 GZCB 光大银行 CEB 温州银行 BOWZ 中信银行 CNCB
        switch($code){
            //北京银行
            case 'BOB':
                $ret = 'BOB';
                break;
            //东亚银行
            case 'BEA':
                $ret = '';
                break;
            //中国工商银行
            case 'ICBC':
                $ret = 'ICBC';
                break;
            //光大银行
            case 'CEB':
                $ret='CEB';
                break;
            //广发银行
            case 'CGB':
                $ret='GDB';
                break;
            //华夏银行
            case 'HXB':
                $ret='HXB';
                break;
            //中国建设银行
            case 'CCB':
                $ret='CCB';
                break;
            //交通银行
            case 'BOCOM':
                $ret='COMM';
                break;
            //中国民生银行
            case 'CMBC':
                $ret='CMBC';
                break;
            //南京银行
            case 'NJCB':
                $ret='';
                break;
            //宁波银行
            case 'NBCB':
                $ret='';
                break;
            //中国农业银行
            case 'ABC':
                $ret='ABC';
                break;
            //平安银行
            case 'PAB':
                $ret='PINGAN';
                break;
            //上海银行
            case 'SHB':
                $ret='';
                break;
            //上海浦东发展银行
            case 'SPDB':
                $ret='SPDB';
                break;
            //深圳发展银行
            case 'SDB':
                $ret='';
                break;
            //兴业银行
            case 'CIB':
                $ret='CIB';
                break;
            //中国邮政储蓄银行
            case 'PSBS':
                $ret='PSBC';
                break;
            //招商银行
            case 'CMB':
                $ret='CMB';
                break;
            //浙商银行
            case 'CZB':
                $ret='';
                break;
            //中国银行
            case 'BOC':
                $ret='BOC';
                break;
            //中信银行
            case 'CTTIC':
                $ret='CNCB';
                break;
            default:
                $this->showmessage('暂不支持此银行卡!',['code'=>'024']);
        }
        if(!$ret){
            $this->showmessage('暂不支持此银行卡!',['code'=>'024']);
        }

        return $ret;
    }
}